'use strict';

const Controller = require('egg').Controller;
const { SuccessModel, ErrorModel } = require('../utils/ResModel');
const { registerUserNameNotExistInfo, registerFailInfo } = require('../utils/ErrorModel');

class UserController extends Controller {
  // 获取登录信息
  getUserInfo() {
    let data = {
      isLogin: false, // 默认未登录
    };

    // 如果用户已经登录
    const userInfo = this.ctx.session.userInfo;
    if (userInfo) {
      data = {
        isLogin: true,
        userName: userInfo.userName,
      };
    }
    return data;
  }
  // 登录页面
  async loginPage() {
    await this.ctx.render('login.html', this.getUserInfo());
  }
  // 注册页面
  async registerPage() {
    await this.ctx.render('register.html', this.getUserInfo());
  }

  // 注册
  async register() {
    const { userName, password, gender } = this.ctx.request.body;
    // 业务逻辑到service
    try {
      await this.service.user.createUser({ userName, password, gender });
      // 注册成功可以什么都不用返回，直接返回成功信息即可，不需要返回数据
      this.ctx.body = new SuccessModel();
    } catch (err) {
      // 打印错误信息,以后讲日志的时候再说， stack错误栈
      console.error(err.message, err.stack);
      // 注册失败，返回注册失败信息
      return new ErrorModel(registerFailInfo);
    }
  }

  // 用户是否存在
  async isExist() {
    // 获取用户名
    const { userName } = this.ctx.request.body;
    const userInfo = await this.service.user.getUserInfo({ userName });
    if (userInfo) {
      this.ctx.body = new SuccessModel();
    } else {
      this.ctx.body = new ErrorModel(registerUserNameNotExistInfo);
    }
  }

  // 登录
  async login() {
    // 获取数据
    const { userName, password } = this.ctx.request.body;
    // 业务逻辑
    const result = await this.service.user.doLogin({ userName, password });

    this.ctx.body = result;
  }


  // 删除用户
  async deleteUser() {
    if (this.app.config.env === 'unittest') {
      const { userName } = this.ctx.session.userInfo;
      const result = await this.service.user.deleteCurrentUser(userName);

      this.ctx.body = result;
    }
  }
}

module.exports = UserController;
